<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="社区ID" prop="communityId">
        <el-input
            v-model="queryParams.communityId"
            placeholder="请输入社区ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通知标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入通知标题"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布人" prop="publisher">
        <el-input
            v-model="queryParams.publisher"
            placeholder="请输入发布人"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker clearable
                        v-model="queryParams.publishTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择发布时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="接受范围" prop="recipientScope">
        <el-input
            v-model="queryParams.recipientScope"
            placeholder="请输入接受范围"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="查看次数" prop="viewCount">
        <el-input
            v-model="queryParams.viewCount"
            placeholder="请输入查看次数"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否删除" prop="isDeleted">
        <el-input
            v-model="queryParams.isDeleted"
            placeholder="请输入是否删除"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['property:notice:add']"
        >添加通知</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['property:notice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['property:notice:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['property:notice:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noticeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="通知ID" align="center" prop="noticeId" width="80" />
      <el-table-column label="社区" align="center" prop="name" width="120" />
      <el-table-column label="通知标题" align="center" prop="title" width="150" />
      <el-table-column label="通知类型" align="center" prop="noticeType" width="100" />
      <el-table-column label="通知内容" align="center" prop="content" width="200">
        <template #default="scope">
          <el-tooltip
              :content="scope.row.content"
              placement="top"
              :disabled="!scope.row.content || scope.row.content.length <= 30"
          >
            <div class="content-cell">
              {{ scope.row.content ? (scope.row.content.length > 30 ? scope.row.content.substring(0, 30) + '...' : scope.row.content) : '-' }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="附件" align="center" prop="attachments" width="120">
        <template #default="scope">
          <el-tooltip
              :content="formatAttachments(scope.row.attachments)"
              placement="top"
              :disabled="!hasAttachments(scope.row.attachments) || getAttachmentText(scope.row.attachments).length <= 20"
          >
            <div class="content-cell">
              {{ getAttachmentDisplayText(scope.row.attachments) }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="发布人" align="center" prop="publisher" width="100" />
      <el-table-column label="发布时间" align="center" prop="publishTime" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接受范围(全体楼宇/指定楼宇)" align="center" prop="recipientScope" width="180" />

      <!-- 固定操作列在右侧 -->
      <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          fixed="right"
          width="200"
      >
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['property:notice:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['property:notice:remove']">删除</el-button>
          <el-button link type="primary" icon="View" @click="handleNoticeDetail(scope.row)" v-hasPermi="['property:notice:view']">通知详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改物业公告对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="社区ID" prop="communityId">
          <el-input v-model="form.communityId" placeholder="请输入社区ID" />
        </el-form-item>
        <el-form-item label="通知标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入通知标题" />
        </el-form-item>
        <el-form-item label="通知内容">
          <el-input
              v-model="form.content"
              type="textarea"
              placeholder="请输入通知内容"
              :rows="6"
              show-word-limit
              maxlength="1000"
          />
        </el-form-item>

        <!-- 修改附件组件为PDF上传组件 -->
        <el-form-item label="附件" prop="attachments">
          <el-upload
              ref="uploadRef"
              class="upload-demo"
              action="#"
              :limit="3"
              :file-list="fileList"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :auto-upload="false"
              accept=".pdf"
          >
            <template #trigger>
              <el-button type="primary">选择PDF文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                只能上传PDF文件，且不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="发布人" prop="publisher">
          <el-input v-model="form.publisher" placeholder="请输入发布人" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker clearable
                          v-model="form.publishTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="接受范围" prop="recipientScope">
          <el-input v-model="form.recipientScope"  />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Notice">
import { listNotice, getNotice, delNotice, addNotice, updateNotice,uploadImage  } from "@/api/property/notice"
import AddNotice from "@/views/property/notice/addNotice.vue";

const { proxy } = getCurrentInstance()

const noticeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const fileList = ref([])
const uploadRef = ref()

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 5,
    communityId: null,
    title: null,
    noticeType: null,
    content: null,
    attachments: null,
    publisher: null,
    publishTime: null,
    recipientScope: null,
    status: null,
    viewCount: null,
    isDeleted: null
  },
  rules: {
  }
})

const { queryParams, form, rules} = toRefs(data)

// 格式化附件显示文本
const formatAttachments = (attachments) => {
  if (!attachments) return '无附件'

  try {
    const attachmentList = JSON.parse(attachments)
    if (Array.isArray(attachmentList) && attachmentList.length > 0) {
      return attachmentList.map(att => att.name).join('、')
    }
    return '无附件'
  } catch (e) {
    return attachments
  }
}

// 获取附件显示文本
const getAttachmentText = (attachments) => {
  return formatAttachments(attachments)
}

// 获取附件显示文本（带截断）
const getAttachmentDisplayText = (attachments) => {
  const text = getAttachmentText(attachments)
  return text.length > 20 ? text.substring(0, 20) + '...' : text
}

// 检查是否有附件
const hasAttachments = (attachments) => {
  if (!attachments) return false

  try {
    const attachmentList = JSON.parse(attachments)
    return Array.isArray(attachmentList) && attachmentList.length > 0
  } catch (e) {
    return false
  }
}

/** 通知详情按钮操作 */
/** 通知详情按钮操作 */
function handleNoticeDetail(row) {
  console.log('当前行数据:', row)

  // 确保从原始数据中获取，而不是代理对象
  const rawData = JSON.parse(JSON.stringify(row))

  // 解析附件信息 - 确保格式正确
  let attachments = []
  try {
    if (rawData.attachments) {
      if (typeof rawData.attachments === 'string') {
        attachments = JSON.parse(rawData.attachments)
      } else if (Array.isArray(rawData.attachments)) {
        attachments = rawData.attachments
      }
    }
  } catch (e) {
    console.error('解析附件数据失败:', e)
    // 如果解析失败，尝试从原始字符串中提取文件名
    if (typeof rawData.attachments === 'string') {
      attachments = [{ name: rawData.attachments, url: '' }]
    }
  }

  // 构建要传递的数据对象
  const noticeData = {
    noticeId: rawData.noticeId,
    communityId: rawData.communityId,
    name: rawData.name,
    title: rawData.title,
    noticeType: rawData.noticeType,
    content: rawData.content,
    attachments: attachments, // 直接传递解析后的数组
    publisher: rawData.publisher,
    publishTime: rawData.publishTime,
    recipientScope: rawData.recipientScope,
    status: rawData.status,
    viewCount: rawData.viewCount,
    isDeleted: rawData.isDeleted
  }

  console.log('准备传递的数据:', noticeData)
  // 跳转到 addNotice 页面
  proxy.$router.push({
    path: '/addNotice',    query: {
      noticeData: JSON.stringify(noticeData)
    }
  })
}


/** 查询物业公告列表 */
function getList() {
  loading.value = true
  listNotice(queryParams.value).then(response => {
    noticeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    noticeId: null,
    communityId: null,
    title: null,
    noticeType: null,
    content: null,
    attachments: null,
    publisher: null,
    publishTime: null,
    recipientScope: null,
    status: null,
    viewCount: null,
    createTime: null,
    updateTime: null,
    isDeleted: null
  }
  fileList.value = []
  proxy.resetForm("noticeRef")
}

// 文件上传前的验证
const beforeUpload = (file) => {
  const isPDF = file.type === 'application/pdf'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isPDF) {
    proxy.$modal.msgError('只能上传PDF格式的文件!')
    return false
  }
  if (!isLt10M) {
    proxy.$modal.msgError('文件大小不能超过10MB!')
    return false
  }
  return true
}

// 处理文件移除
const handleRemove = (file, files) => {
  // 更新文件列表
  updateAttachments(files)
}

// 处理文件变化
const handleChange = (file, files) => {
  // 验证文件格式和大小
  if (file.raw) {
    const isValid = beforeUpload(file.raw)
    if (!isValid) {
      // 移除无效文件
      const index = files.indexOf(file)
      if (index > -1) {
        files.splice(index, 1)
      }
      return
    }
  }

  // 更新文件列表
  updateAttachments(files)
}

// 更新附件数据
const updateAttachments = (files) => {
  // 将文件列表转换为JSON字符串格式，存储文件信息
  const attachments = files.map(file => ({
    name: file.name,
    url: file.url || '', // 如果有上传后的URL
    size: file.size,
    uid: file.uid
  }))

  form.value.attachments = JSON.stringify(attachments)
}

const toolbars = {
  bold: true,          // 粗体
  italic: true,        // 斜体
  header: true,        // 标题
  underline: true,     // 下划线
  strikethrough: true, // 删除线
  image: true,         // 插入图片
  table: true,         // 插入表格
  fullscreen: true     // 全屏
}
// 图片添加回调
const handleImgAdd = (file, insertImg) => {
  // 这里实现图片上传逻辑
  uploadImage(file).then(url => {
    insertImg(url) // 插入图片到编辑器
  })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.noticeId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 添加通知按钮操作 */
function handleAdd() {
  // 跳转到 detailNotice 页面进行添加
  proxy.$router.push('/detailNotice?mode=add')
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _noticeId = row.noticeId || ids.value
  getNotice(_noticeId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改物业公告"

    // 初始化文件列表
    if (form.value.attachments) {
      try {
        const attachments = JSON.parse(form.value.attachments)
        fileList.value = attachments.map(att => ({
          name: att.name,
          url: att.url,
          size: att.size,
          uid: att.uid
        }))
      } catch (e) {
        console.error('解析附件数据失败:', e)
        fileList.value = []
      }
    } else {
      fileList.value = []
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate(valid => {
    if (valid) {
      if (form.value.noticeId != null) {
        updateNotice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addNotice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _noticeIds = row.noticeId || ids.value
  proxy.$modal.confirm('是否确认删除物业公告编号为"' + _noticeIds + '"的数据项？').then(function() {
    return delNotice(_noticeIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('property/notice/export', {
    ...queryParams.value
  }, `notice_${new Date().getTime()}.xlsx`)
}

getList()
</script>
<style scoped>
.content-cell {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.text-ellipsis {
  display: inline-block;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

/* 如果需要多行显示 */
.multi-line-ellipsis {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
  max-height: 2.8em;
}

/* 确保表格容器有适当的样式 */
.app-container {
  width: 100%;
  overflow: hidden;
}

/* 为表格容器添加横向滚动 */
:deep(.el-table) {
  min-width: 100%;
}

:deep(.el-table .el-table__fixed-right) {
  height: 100% !important;
  background-color: #fff;
}

.upload-demo {
  width: 100%;
}
</style>